package commons
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.errors.IllegalOperationError;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	
	import commons.cache.SourceCache;
	
	import events.loader.CacheEvent;

	/**
	 *图片映像类
	 *Dont小鬼
	 *2013-12-26
	 */
	public class ImgReflection extends EventDispatcher
	{
		/**加载图片完成*/
		public static const LoadBitCom:String="ImgReflection.LoadBitCom";

		private static var _instance:ImgReflection=null;
		private static var _allowInstance:Boolean=false;

		private var _pathListArr:Array=[];
		private var _idx:uint=0;

		public function ImgReflection()
		{
			if (!_allowInstance)
				throw new IllegalOperationError("不能实例化ImgReflection类");
		}

		public static function getInstance():ImgReflection
		{
			if (null == _instance)
			{
				_allowInstance=true;
				_instance=new ImgReflection();
				_allowInstance=false;
			}
			return _instance;
		}

		/**
		 * 根据路径获取图片的bitmap
		 * @param path
		 * @return
		 */
		public function BitmapInstance(path:String):BitmapData
		{
			var bitData:BitmapData=null;
				if (SourceCache.getInstance().has(path))
				{
					bitData=(SourceCache.getInstance().getObject(path) as BitmapData).clone();
					_instance.dispatchEvent(new Event(LoadBitCom));
				}
				else
				{
					SourceCache.getInstance().addEventListener(Event.COMPLETE, loadedImageComplete);
					if (!SourceCache.getInstance().isLoading(path))
					{
						_pathListArr.push(path);
						SourceCache.getInstance().load(path);
					}
				}


			function loadedImageComplete(loader:CacheEvent):void
			{
				if (loader&&loader.url == path)
				{
					bitData=(SourceCache.getInstance().getObject(path) as BitmapData).clone();
					_instance.dispatchEvent(new Event(LoadBitCom));

					_idx=_pathListArr.indexOf(loader.url);
					if (_idx != -1)
						_pathListArr.splice(_idx, 1);

					if (_pathListArr.length == 0)
						SourceCache.getInstance().removeEventListener(Event.COMPLETE, loadedImageComplete);
				}
			}
			return bitData;
		}

		/**
		 * 创建图形实例
		 * @param className
		 * @return
		 */
		public function createDisplayObject(theClass:Class):*
		{
			var c:*=new theClass();
			return c as DisplayObject;
		}
	}
}
